package com.lyc.controller.user;


import com.lyc.DTO.PostDTO;
import com.lyc.pojo.Post;
import com.lyc.pojo.*;
import com.lyc.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j// 日志
@RequestMapping("/post")
public class PostController {
    @Autowired
    private PostService postService;

    //添加帖子
    @PostMapping("/add")
    public Result<String> add(@RequestPart("post") Post post,
                              @RequestPart(value = "covers", required = false) MultipartFile[] coverFiles,
                              @RequestPart(value = "cover", required = false) MultipartFile coverFile) {
        try {
            // 处理多图片上传
            if (coverFiles != null && coverFiles.length > 0) {
                postService.addPostWithCover(post, coverFiles);
                return Result.success("添加成功");
            }
            // 处理单图片上传（向后兼容）
            else if (coverFile != null && !coverFile.isEmpty()) {
                postService.addPostWithCover(post, new MultipartFile[]{coverFile});
                return Result.success("添加成功");
            }
            // 没有提供图片
            else {
                return Result.error("至少需要提供一张图片");
            }
        } catch (Exception e) {
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    //获取全部帖子
    @GetMapping("/all")
    public Result<List<Post>> getAllPosts(){
        List<Post> list = postService.getAllPosts();
        return Result.success(list);
    }

    //获取用户帖子列表--分页查询
    @GetMapping("/personage")
    public Result<PageBean<Post>> getUserPostInfo(Integer pageNum, Integer pageSize){
        PageBean<Post> pageBean = postService.getUserPostInfo(pageNum, pageSize);
        return Result.success(pageBean);
    }

    // 根据用户ID获取帖子列表（不使用分页）
    @GetMapping("/list")
    public Result<List<Post>> getPostListByUserId(@RequestParam(required = false) Integer userId) {
        List<Post> posts;
        posts = postService.getPostsByUserId(userId);
        return Result.success(posts);
    }

    //获取帖子详情
    @GetMapping("/detail")
    public Result<Post> getPostDetail(Integer id){
        Post post = postService.getPostDetail(id);
        return Result.success(post);
    }

    //获取帖子分类
    @GetMapping("/categories")
   public Result<List<Category>> getCategories(){
        List<Category> list = postService.getCategories();
        return Result.success(list);
    }

    //获取帖子封面
    @GetMapping("/cover")
    public Result<List<PostImages>> getCover(){
        List<PostImages> list = postService.getCover();
        return Result.success(list);
    }

    //获取热门帖子
    @GetMapping("/hot")
    public Result<List<Post>> getHotPosts() {
        List<Post> hotPosts = postService.getHotPosts(); // 按viewCount排序并取前5个
        return Result.success(hotPosts);
    }

    // 按浏览量降序排序
    @GetMapping("/sort")
    public Result<List<Post>> sortByViewCount() {
        List<Post> sortedPosts = postService.selectAllOrderByViewCountDesc();
        sortedPosts.sort((post1, post2) -> post2.getViewCount() - post1.getViewCount());
        return Result.success(sortedPosts);
    }

    // 根据帖子ID获取封面图片
    @GetMapping("/coverById")
    public Result<List<PostImages>> getCoverById(Integer postId) {
        List<PostImages> coverList = postService.getCoverById(postId);
        return Result.success(coverList);
    }

    // 获取二手/失物帖子的商品类别
    @GetMapping("/itemType")
    public Result<List<ItemType>> getItemTypes(Integer categoryId) {
        List<ItemType> itemTypes = postService.getItemTypes(categoryId);
        return Result.success(itemTypes);
    }

    // 获取二手/失物帖子的商品--分页查询
    @GetMapping("/paging/items")
    public Result<PageBean<Post>> getItemList(Integer categoryId,
                                              @RequestParam(defaultValue = "1") Integer pageNum,
                                              @RequestParam(defaultValue = "6") Integer pageSize){
        PageBean<Post> pageBean = postService.getItemList(categoryId,pageNum, pageSize);
        return Result.success(pageBean);
    }

    //获取二手/失物帖子的商品
    @GetMapping("/items")
        public Result<List<Post>> getItemLists(Integer categoryId) {
            List<Post> itemList = postService.getItemLists(categoryId);
            return Result.success(itemList);
        }


    // 增加帖子浏览量
    @PostMapping("/increment-view/{id}")
    public Result<String> incrementViewCount(@PathVariable Integer id) {
        try {
            postService.incrementViewCount(id);
            return Result.success("浏览量增加成功");
        } catch (Exception e) {
            return Result.error("增加浏览量失败");
        }
    }

    //修改用户帖子
    @PutMapping("/update")
    public Result update(@RequestBody @Validated PostDTO postDTO){
        postService.update(postDTO);
        return Result.success("修改成功");
    }

    //修改用户帖子封面--阿里云存储
//    @PatchMapping("/updateCover")
//    public Result updateCover(@RequestBody Map<String, Object> requestMap) {
//            String imageUrl = (String) requestMap.get("imageUrl");
//            Integer postId = (Integer) requestMap.get("postId");
//            postService.updateCover(imageUrl, postId);
//            return Result.success("修改成功");
//    }

    // 修改用户帖子封面--本地存储
    @PatchMapping("/uploadCover")
    public Result<String> uploadCover(@RequestParam("file") MultipartFile file,
                                      @RequestParam("postId") Integer postId) {
        try {
            // 调用服务层处理文件上传
            String filePath = postService.uploadCover(file,postId);
            return Result.success(filePath);
        } catch (Exception e) {
            return Result.error("上传失败");
        }
    }

    // 批量/单个修改帖子状态
    @PutMapping("/batchUpdateStatus")
    public Result batchUpdateStatus(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> postIds = (List<Integer>) request.get("postIds");
            String status = (String) request.get("status");

            if (postIds == null || postIds.isEmpty()) {
                return Result.error("帖子ID列表不能为空");
            }

            if (status == null || status.isEmpty()) {
                return Result.error("状态不能为空");
            }

            // 验证状态值是否合法
            if (!"pending".equals(status) && !"approved".equals(status) && !"rejected".equals(status) && !"sold".equals(status)) {
                return Result.error("状态值不合法，只能为'pending'、'approved'、'rejected'或'sold'");
            }

            postService.batchUpdatePostStatus(postIds, status);
            return Result.success("帖子状态更新成功");
        } catch (Exception e) {
            return Result.error("帖子状态更新失败: " + e.getMessage());
        }
    }



    // 删除用户帖子封面
    @DeleteMapping("/deleteCover")
    public Result<String> deleteCover(@RequestParam("id") Integer id) {
        try {
            postService.deleteCover(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除失败");
        }
    }

    //删除用户帖子
    @DeleteMapping("/delete")
    public Result<String> deletePost(Integer id){
        postService.deletePost(id);
        return Result.success("删除成功");
    }
}